package com.test.designpattern.chainOfResponsibility.demo1;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

//执行器类，责任链执行入口
@Component
public class AuditChainExcutor {

    @Autowired
    public List<IAuditHandler> auditHandlers;

    //执行器排序
    public AuditChainExcutor(List<IAuditHandler> auditHandlers) {
        this.auditHandlers = auditHandlers.stream().sorted(Comparator.comparing(IAuditHandler::getOrder)).collect(Collectors.toList());

        //给每个处理器，设置下一个处理器
        IntStream.range(0, auditHandlers.size() - 1).forEach(i -> {
            if (i < auditHandlers.size() - 1) {
                IAuditHandler handler = auditHandlers.get(i);
                handler.setNextHandler(auditHandlers.get(i + 1));
            }
        });
    }

    //方法入口
    public void startChain(Object o){
        System.out.println("责任链执行开始...");
        IAuditHandler handler = auditHandlers.get(0);
        handler.handler(o);
    }
}
